<template>
	<view
	:class="'browser' + dataId"
	class="find_browser"
	:data-theme="theme"
	:ready="ready" :change:ready="browser.readyWatcher"
	:src="src" :change:src="browser.srcWatcher"
	:theme="theme" :change:theme="browser.themeWatcher"
	:jump="jump" :change:jump="browser.jumpWatcher">
	</view>
</template>

<script>
	export default {
		props: {
			dataId: {
				type: String,
				default () {
					let mydate = new Date()
					return 'cms' + mydate.getMinutes() + mydate.getSeconds() + mydate.getMilliseconds() + Math.round(Math.random() * 10000)
				}
			},
			src: {
				type: String,
				default: ''
			},
			theme: {
				type: String,
				default: ''
			}
		},
		data () {
			return {
				ready: '',
				jump: 0
			}
		},
		mounted () {
			this.$nextTick(function () {
				setTimeout(() => {
					this.ready = this.dataId
				}, 100)
			})
		},
		methods: {
			loadstart () {
				this.$emit('loadstart')
			},
			loaded (e) {
				this.$emit('loaded', e)
			},
			backerror () {
				this.$emit('backerror')
			},
			back () {
				this.jump = 0
				this.$nextTick(function () {
					this.jump = -1
				})
			}
		}
	}
</script>
<!-- #ifdef APP-VUE || H5 -->
<script lang="renderjs" type="module" module="browser">
	export default {
		data () {
			return {
				dom: null,
				iframe: null,
				loading: null,
				iframeSrc: '',
				backTimer: null
			}
		},
		mounted () {
			window.onbeforeunload = (e) => {
				e.preventDefault();
				e.returnValue = '已阻止本次跳转，此跳转可能会出现意想不到的问题';
			}
			// window.onmessage = (e) => {
			// 	console.log('e', e.origin);
			// }
		},
		methods: {
			destoryIframe () {
				if ( this.loading ) {
					this.loading.remove()
					this.loading = null
				}
				if ( this.iframe ) {
					this.iframe.remove()
					this.iframe = null
				}
			},
			showLoading () {
				if ( this.loading ) this.loading.setAttribute('class', 'browser-loading-line browser-loading-show')
			},
			hideLoading () {
				if ( this.loading ) this.loading.setAttribute('class', 'browser-loading-line browser-loading-hide')
			},
			clearBackTimer () {
				if ( this.backTimer ) {
					window.clearTimeout(this.backTimer)
					this.backTimer = null
				}
			},
			initIframe () {
				this.showLoading()
				this.callMethod('loadstart')
				this.iframe = document.createElement('IFRAME')
				this.iframe.setAttribute('class', 'find_browser_iframe find_browser_iframe_' + this.getData('theme'))
				this.iframe.setAttribute('frameborder', '0')
				this.iframe.setAttribute('allowfullscreen', true)
				// this.iframe.setAttribute('sandbox', 'allow-scripts allow-forms allow-same-origin')
				this.iframe.src = this.iframeSrc
				this.iframe.onload = () => {
					this.hideLoading()
					const iframeWindow = this.iframe.contentWindow
					iframeWindow.onbeforeunload = (event) => {
						this.clearBackTimer()
						this.callMethod('loadstart')
						this.showLoading()
					}
					const iframeDocument = this.iframe.contentDocument || iframeWindow.document;
					const style = iframeDocument.createElement('STYLE')
					style.innerHTML = `
						img, video, audio { 
							filter: invert(${this.getData('theme') == 'dark' ? 1 : 0})!important;
						}
					`
					iframeDocument.head.appendChild(style)
					// iframeDocument.addEventListener('click', function(e) {
					//     const link = e.target.closest('a');
					// 	console.log('click', link);
					//     if (link) {
					// 		console.log('click', link);
					//         e.preventDefault();
					//         const url = link.href;
					//         // 发送消息到父页面
					//         iframeWindow.parent.postMessage({ type: "navigation", url }, "http://parent-domain.com");
					//         // 可以选择在这里加载链接
					//         iframeWindow.location = url;
					//     }
					// });
					const history = iframeWindow.history
					this.callMethod('loaded', {title: iframeDocument.title, href: iframeWindow.location.href, histroy: []})
				}
				this.iframe.onerror = () => {
					this.hideLoading()
				}
				this.dom.appendChild(this.iframe)
				Object.keys(this.iframe.contentWindow.console).forEach(key => {
					this.iframe.contentWindow.console[key] = function () {}
				})
			},
			readyWatcher (newVal) {
				if ( newVal ) {
					this.dom = document.querySelector('.browser' + newVal)
					this.loading = document.createElement('DIV')
					this.loading.setAttribute('class', 'browser-loading-line')
					this.dom.appendChild(this.loading)
				}
				if ( this.iframeSrc && this.dom ) this.initIframe()
			},
			srcWatcher (newVal, oldVal) {
				this.iframeSrc = newVal
				if ( !this.dom ) return
				if ( newVal != oldVal ) {
					if ( oldVal ) this.destoryIframe()
					if ( newVal ) this.initIframe()
				}
			},
			themeWatcher (newVal) {
				this.setTheme(newVal)
			},
			jumpWatcher (newVal) {
				if ( newVal < 0 && this.iframe ) {
					this.iframe.contentWindow.history.back()
					this.backTimer = window.setTimeout(() => {
						this.callMethod('backerror')
					}, 300)
				}
			},
			setTheme (theme) {
				if ( this.iframe ) {
					this.iframe.setAttribute('class', 'find_browser_iframe find_browser_iframe_' + theme)
					const iframeDocument = this.iframe.contentDocument || this.iframe.contentWindow.document;
					const styles = iframeDocument.getElementsByTagName('style')
					let style
					for ( let i = 0; i < styles.length; i++ ) {
						if ( styles[i].getAttribute('data-type') == 'theme' ) style = styles[i]
					}
					if ( !style ) {
						style = iframeDocument.createElement('STYLE')
						style.setAttribute('data-type', 'theme')
						iframeDocument.head.appendChild(style)
					}
					style.innerHTML = `
						img, video, audio { 
							filter: invert(${theme == 'dark' ? 1 : 0})!important;
						}
					`
				}
			},
			getData (name) {
				const value = this.dom.getAttribute('data-' + name)
				if ( ['true', 'false'].includes(value) ) return value == 'false' ? false : true
				else if ( /[0-9]/.test(value) ) return Number(value)
				else return value
			},
			callMethod (name, args) {
				// #ifndef H5
				this.$ownerInstance.callMethod(name, args)
				// #endif
				// #ifdef H5
				this[name](args)
				// #endif
			}
		}
	}
</script>
<!-- #endif -->


<style>
	@keyframes loading-show {
		from {
			width: 0;
		}
		to {
			width: 99%;
		}
	}
	@keyframes loading-hide {
		from {
			width: 0;
			opacity: 1;
		}
		to {
			width: 100%;
			opacity: 0;
		}
	}
	.find_browser {
		position: relative;
	}
	/deep/ .find_browser_iframe {
		width: 100%;
		height: 100%;
	}
	/deep/ .find_browser_iframe_dark:fullscreen {
	    filter: none;
	}
	/deep/ .find_browser_iframe_dark {
		filter: invert(1);
	}
	/deep/ .find_browser_iframe_light {
		filter: none;
	}
	/deep/ .browser-loading-line {
		position: absolute;
		top: 0;
		left: 0;
		width: 0;
		height: 3px;
		border-radius: 3px;
		background-color: #4cd964;
		z-index: 1;
		touch-action: none;
		pointer-events: none;
	}
	/deep/ .browser-loading-show {
		animation: loading-show 5s ease both;
	}
	/deep/ .browser-loading-hide {
		animation: loading-hide .5s linear both;
	}
</style>